import { Button, Col, Divider, Icon, Row, Table, Tag } from 'antd'
import React, { Component } from 'react'
import { connect } from 'react-redux'
import '../../less/index.less'
import { withRouter } from 'react-router-dom'
import * as action from '../../actions/assignment'
import { parse } from 'qs'
import moment from 'moment'
import PreviewModal from './preview-quiz/index'
import SearchBox from './search-box'
import getQuizType from '../../constant/quiz-type-app-address'
import { FormattedMessage } from 'react-intl'

const MAP_BASIC_QUIZ_TYPE = {
  MULTIPLE_CHOICE: '多选题',
  SINGLE_CHOICE: '单选题',
  BASIC_BLANK_QUIZ: '填空题'
}

class QuizzesModel extends Component {
  constructor () {
    super()
    this.state = {
      taskId: -1,
      programId: -1,
      type: '',
      page: 1,
      pageSize: 10,
      visible: false,
      assignmentId: -1,
      quiz: {},
      selectedRowKeys: [],
      searchConditions: {}
    }
  }

  componentDidMount () {
    const query = parse(this.props.location.search.substr(1))
    this.setState({
      taskId: this.props.match.params.taskId,
      programId: this.props.match.params.programId,
      assignmentId: this.props.match.params.assignmentId,
      type: query.type
    }, () => {
      const {type, page, pageSize, assignmentId, searchConditions} = this.state
      this.props.getQuizzes(type, page, pageSize, searchConditions)
      this.props.getAssignment(assignmentId)
    })
  }

  componentWillReceiveProps (nextProps) {
    const {selectedQuizzes} = nextProps.assignment
    if (selectedQuizzes && this.props.assignment !== nextProps.assignment) {
      const selectedQuizIds = selectedQuizzes.map(selectedQuiz => selectedQuiz.quizId)
      this.setState({selectedRowKeys: selectedQuizIds})
    }
  }

  onChange (page) {
    this.setState({page})
    const {pageSize, searchConditions} = this.state
    this.props.getQuizzes(this.state.type, page, pageSize, searchConditions)
  }

  previewPage (quiz) {
    this.setState({
      visible: true,
      quiz
    })
  }

  start () {
    const {selectedRowKeys, taskId, assignmentId} = this.state
    this.props.addAssignmentQuiz(selectedRowKeys, taskId, assignmentId)
    this.setState({
      selectedRowKeys: []
    }, () => {
      window.history.back(-1)
    })
  }

  onSelectChange (selectedRowKeys) {
    this.setState({selectedRowKeys})
  }

  closeModal () {
    this.setState({
      visible: false,
      quiz: {}
    })
  }

  onSearch (searchConditions) {
    this.setState({searchConditions})
    const {page, pageSize} = this.state
    this.props.getQuizzes(this.state.type, page, pageSize, searchConditions)
  }

  toCreteQuizPage () {
    console.log(this.state.type)
    const addressSuffix = getQuizType(this.state.type)
    const address = `/learn${addressSuffix}`
    window.open(address + 'new')
  }

  toEditPage (record) {
    const addressSuffix = getQuizType(record.type || this.state.type)
    const address = `/learn${addressSuffix}`
    window.open(address + record.id + '/editor')
  }

  render () {
    const {content, totalElements} = this.props.quizzesInfo
    const {visible, quiz} = this.state
    const {type} = this.props.assignment
    const quizzes = content.map(quiz => {
      quiz.createTime = moment(quiz.createTime).format('YYYY-MM-DD')
      if (quiz.tags) {
        const tags = quiz.tags.map(tag => <Tag key={tag.id}>{tag.name}</Tag>)
        return Object.assign({}, quiz, {tags})
      }
      return quiz
    })

    const columns = [{
      title: 'IDS',
      width: '5%',
      dataIndex: 'id'
    }, {
      title: <FormattedMessage id='题目描述' />,
      dataIndex: 'description',
      width: '35%',
      className: 'description-style'
    }, {
      title: <FormattedMessage id='标题' />,
      dataIndex: 'remark',
      className: type === 'HOMEWORK_QUIZ' || type === 'SUBJECTIVE_QUIZ' || type === 'ONLINE_LANGUAGE_QUIZ' ? '' : 'hidden'
    }, {
      title: <FormattedMessage id='标签' />,
      dataIndex: 'tags',
      className: type === 'LOGIC_QUIZ' ? 'hidden' : '',
      sorter: (a, b) => a.tags.length - b.tags.length
    }, {
      title: <FormattedMessage id='创建时间' />,
      dataIndex: 'createTime',
      sorter: (a, b) => a.createTime.length - b.createTime.length
    }, {
      title: <FormattedMessage id='创建者' />,
      dataIndex: 'maker',
      sorter: (a, b) => a.maker.length - b.maker.length
    }, {
      title: <FormattedMessage id='类型' />,
      dataIndex: 'type',
      sorter: (a, b) => a.type.length - b.type.length,
      className: type === 'BASIC_QUIZ' ? '' : 'hidden',
      render: (text) => {
        return MAP_BASIC_QUIZ_TYPE[text] || ''
      }
    }, {
      title: <FormattedMessage id='操作' />,
      key: 'action',
      render: (text, record) => (
        <span>
          <Icon type='eye' className='icon-style' onClick={this.previewPage.bind(this, record)} />
          <Divider type='vertical' />
          <Icon type='edit' className='icon-style' onClick={this.toEditPage.bind(this, record)} />
        </span>)
    }]
    const pagination = {
      current: this.state.page,
      total: totalElements,
      pageSize: this.state.pageSize,
      onChange: (page) => {
        this.onChange(page, this.state.pageSize)
      }
    }
    const {loading, selectedRowKeys} = this.state
    const hasSelected = selectedRowKeys.length > 0

    const rowSelection = {
      selectedRowKeys,
      type: type === 'BASIC_QUIZ' || type === 'SURVEY_QUIZ' ? 'checkbox' : 'radio',
      onChange: this.onSelectChange.bind(this)
    }

    return (
      <div>
        <div style={{marginBottom: 16}}>
          <Row gutter={16}>
            <Col span={8}>
              <Button
                type='primary'
                onClick={this.start.bind(this)}
                disabled={!hasSelected}
                loading={loading}
              >
                <FormattedMessage id='确定并返回' />
              </Button>
              <Divider type='vertical' />
              <Button onClick={() => { window.history.back(-1) }}><FormattedMessage id='返回' /></Button>
            </Col>
          </Row>
          <Row style={{marginTop: 10}}>
            <Col span={20}>
              <SearchBox onSearch={this.onSearch.bind(this)} />
            </Col>
            <Col span={4}>
              <Button onClick={this.toCreteQuizPage.bind(this)}><FormattedMessage id='新增题目' /></Button>
            </Col>
          </Row>
        </div>
        <div><FormattedMessage id='已选择题目Id' />：{this.state.selectedRowKeys.join(',')}</div>
        <div className='table-style'>
          <Table rowKey={record => record.id}
            columns={columns}
            dataSource={quizzes}
            pagination={pagination}
            bordered
            rowSelection={rowSelection}
            className='table-center' />
        </div>
        <PreviewModal visible={visible}
          quiz={quiz}
          type={type}
          closeModal={this.closeModal.bind(this)}
        />
      </div>
    )
  }
}

const mapStateToProps = ({taskInfo, settings}) => ({
  quizzesInfo: taskInfo.quizzesInfo,
  assignment: taskInfo.assignment,
  settings
})

const mapDispatchToProps = dispatch => ({
  getQuizzes: (type, page, pageSize, searchConditions) => dispatch(action.getQuizzes(type, page, pageSize, searchConditions)),
  addAssignmentQuiz: (selectedRowKeys, taskId, assignmentId) => dispatch(action.addAssignmentQuiz(selectedRowKeys, taskId, assignmentId)),
  getAssignment: (assignmentId) => dispatch(action.getAssignment(assignmentId))
})
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(QuizzesModel))
